import React, { useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Grid,
  Card,
  CardContent,
  Divider,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  Stack,
  Snackbar,
  MenuItem,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';

interface Education {
  id: number;
  school: string;
  degree: string;
  field_of_study: string;
  start_date: string;
  end_date: string | null;
  description: string;
  user_id: number;
}

interface EducationProps {
  educations: Education[];
  onUpdate: () => void;
}

const degreeOptions = [
  { value: '高中', label: '高中' },
  { value: '大专', label: '大专' },
  { value: '本科', label: '本科' },
  { value: '硕士', label: '硕士' },
  { value: '博士', label: '博士' },
  { value: '其他', label: '其他' },
];

const formatDate = (dateString: string | null) => {
  if (!dateString) return '至今';
  
  // 假设日期格式为 YYYY-MM-DD
  const parts = dateString.split('-');
  if (parts.length >= 2) {
    return `${parts[0]}年${parts[1]}月`;
  }
  return dateString;
};

const Education: React.FC<EducationProps> = ({ educations, onUpdate }) => {
  const [open, setOpen] = useState(false);
  const [editingEdu, setEditingEdu] = useState<Education | null>(null);
  const [formData, setFormData] = useState({
    school: '',
    degree: '本科',
    field: '',
    start_date: '',
    end_date: '',
    description: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const resetForm = () => {
    setFormData({
      school: '',
      degree: '本科',
      field: '',
      start_date: '',
      end_date: '',
      description: '',
    });
    setEditingEdu(null);
    setError('');
  };

  const handleOpenDialog = (edu?: Education) => {
    if (edu) {
      setEditingEdu(edu);
      setFormData({
        school: edu.school,
        degree: edu.degree,
        field: edu.field_of_study,
        start_date: edu.start_date.split('T')[0],
        end_date: edu.end_date ? edu.end_date.split('T')[0] : '',
        description: edu.description,
      });
    } else {
      resetForm();
    }
    setOpen(true);
  };

  const handleCloseDialog = () => {
    setOpen(false);
    resetForm();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async () => {
    setLoading(true);
    setError('');

    try {
      // 验证表单
      if (!formData.school || !formData.degree || !formData.field) {
        throw new Error('学校、学历和专业不能为空');
      }

      // 验证日期格式 (YYYY-MM-DD)
      if (formData.start_date) {
        const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
        if (!dateRegex.test(formData.start_date)) {
          throw new Error('开始日期格式无效，请使用YYYY-MM-DD格式');
        }
      }

      if (formData.end_date) {
        const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
        if (!dateRegex.test(formData.end_date)) {
          throw new Error('结束日期格式无效，请使用YYYY-MM-DD格式');
        }
      }

      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      const payload = {
        ...formData,
        field_of_study: formData.field,
        end_date: formData.end_date || null,
      };

      const url = editingEdu 
        ? `/api/user/education/${editingEdu.id}` 
        : '/api/user/education';

      const method = editingEdu ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '保存教育经历失败');
      }

      setSuccessMessage(editingEdu ? '教育经历更新成功' : '教育经历添加成功');
      setSuccess(true);
      handleCloseDialog();
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    setDeletingId(id);
    setDeleteConfirmOpen(true);
  };

  const confirmDelete = async () => {
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      const response = await fetch(`/api/user/education/${deletingId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || '删除教育经历失败');
      }

      setSuccessMessage('教育经历删除成功');
      setSuccess(true);
      setDeleteConfirmOpen(false);
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
      setDeletingId(null);
    }
  };

  return (
    <Box sx={{ py: 2 }}>
      <Snackbar 
        open={success} 
        autoHideDuration={3000} 
        onClose={() => setSuccess(false)} 
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="success" onClose={() => setSuccess(false)}>
          {successMessage}
        </Alert>
      </Snackbar>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h5" component="h2">教育经历</Typography>
        <Button 
          startIcon={<AddIcon />} 
          variant="contained" 
          color="primary"
          onClick={() => handleOpenDialog()}
        >
          添加教育经历
        </Button>
      </Box>

      {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}

      {educations.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 4 }}>
          <Typography variant="body1" color="textSecondary">
            暂无教育经历，点击"添加教育经历"按钮开始添加
          </Typography>
        </Box>
      ) : (
        <Stack spacing={2}>
          {educations.map((edu) => (
            <Card key={edu.id} sx={{ mb: 2 }}>
              <CardContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <Box>
                    <Typography variant="h6" component="h3">{edu.school}</Typography>
                    <Typography variant="subtitle1">
                      {edu.degree}・{edu.field_of_study}
                    </Typography>
                    <Typography variant="body2" color="textSecondary">
                      {formatDate(edu.start_date)} - {formatDate(edu.end_date)}
                    </Typography>
                  </Box>
                  <Box>
                    <IconButton 
                      size="small" 
                      color="primary"
                      onClick={() => handleOpenDialog(edu)}
                    >
                      <EditIcon />
                    </IconButton>
                    <IconButton 
                      size="small" 
                      color="error"
                      onClick={() => handleDelete(edu.id)}
                    >
                      <DeleteIcon />
                    </IconButton>
                  </Box>
                </Box>
                {edu.description && (
                  <>
                    <Divider sx={{ my: 1.5 }} />
                    <Typography variant="body1" sx={{ whiteSpace: 'pre-line' }}>
                      {edu.description}
                    </Typography>
                  </>
                )}
              </CardContent>
            </Card>
          ))}
        </Stack>
      )}

      {/* 添加/编辑教育经历对话框 */}
      <Dialog 
        open={open} 
        onClose={handleCloseDialog}
        fullWidth
        maxWidth="md"
      >
        <DialogTitle>
          {editingEdu ? '编辑教育经历' : '添加教育经历'}
        </DialogTitle>
        <DialogContent>
          {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="学校名称"
                name="school"
                value={formData.school}
                onChange={handleChange}
                required
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                select
                fullWidth
                label="学历"
                name="degree"
                value={formData.degree}
                onChange={handleChange}
                required
              >
                {degreeOptions.map((option) => (
                  <MenuItem key={option.value} value={option.value}>
                    {option.label}
                  </MenuItem>
                ))}
              </TextField>
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="专业"
                name="field"
                value={formData.field}
                onChange={handleChange}
                required
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="开始日期 (YYYY-MM-DD)"
                name="start_date"
                value={formData.start_date}
                onChange={handleChange}
                placeholder="例如：2020-09-01"
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="结束日期 (YYYY-MM-DD，留空表示至今)"
                name="end_date"
                value={formData.end_date}
                onChange={handleChange}
                placeholder="例如：2024-06-30"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="在校经历描述"
                name="description"
                value={formData.description}
                onChange={handleChange}
                multiline
                rows={4}
                placeholder="在校成绩、获奖情况、社团活动等"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>取消</Button>
          <Button 
            onClick={handleSubmit} 
            variant="contained" 
            color="primary"
            disabled={loading}
          >
            {loading ? '保存中...' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>确定要删除此教育经历记录吗？此操作无法撤销。</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteConfirmOpen(false)}>取消</Button>
          <Button 
            onClick={confirmDelete} 
            color="error" 
            variant="contained"
            disabled={loading}
          >
            {loading ? '删除中...' : '确认删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Education; 